﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow.Domain;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using Yitter.IdGenerator;

namespace Workflow.Application.Step
{
    public class AuditStep : StepBody
    {
        private readonly WorkflowContext db;

        public AuditStep(WorkflowContext db)
        {
            this.db = db;
        }
        public long AuditUserId {  get; set; }
        public string AuditUserName { get; set; }
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            if (!context.ExecutionPointer.EventPublished) 
            {
                db.audit.Add(new ()
                {
                    ID=YitIdHelper.NextId().ToString(),
                    WorkflowId=context.Workflow.Id,
                    StepId=context.Step.ExternalId,
                    StepName=context.Step.Name,
                    AuditUserId=AuditUserId,
                    AuditUserName=AuditUserName,
                    ExecutionPointerId=context.ExecutionPointer.Id,
                    IsDeleted=false,
                    Status=false,
                    AuditOperation=string.Empty,
                    Remark=string.Empty,
                });
                db.SaveChanges();
                var model=db.instance.FirstOrDefault(x=>x.WorkflowId==context.Workflow.Id);
                model.StepName=context.Step.Name;
                model.AuditUserName=AuditUserName;
                db.instance.Update(model);
                db.SaveChanges();
                Console.WriteLine($"等待{AuditUserName}审批。。。。");
                return ExecutionResult.WaitForEvent("MyEvent",context.Workflow.Id,DateTime.Now);
            }
            Console.WriteLine($"审批成功，审批意见是：{context.ExecutionPointer.EventData}");
            return ExecutionResult.Next();
        }
    }
}
